#include "stdafx.h"
#include "TF2DHooker.h"

TF2DHooker* TF2DHooker::_instance = 0;


TF2DHooker::TF2DHooker()
{
	wasEndPageLoad = 0;
	callOutputDebugStringWOrg = 0;
	_instance = this;
}

TF2DHooker* TF2DHooker::get_Instance()
{
	if (!_instance)
		_instance = new TF2DHooker();
	return _instance;
}

void TF2DHooker::Initialize(Logger* logger, TODAYTABSETTINGS* settings)
{
}

HWND TF2DHooker::GetManilaWindow()
{
	return FindWindow (L"HTCManila2D", 0);
}

void TF2DHooker::OutputDebugStringWSubst(LPCWSTR lpszFmt)
{
	OutputDebugStringW(lpszFmt);
	
	if (wcsicmp(lpszFmt, L"HTCHome InternetWidget::OnActivate() Start\r\n") == 0)
	{
		_callback(true);
		wasEndPageLoad = 0;
	}
	else
	{
		if (wcsicmp(lpszFmt, L"HTCHome InternetWidget::OnActivate() End\r\n") == 0)
		{
			wasEndPageLoad = 1;
		}
		else
		{
			if (wasEndPageLoad)
			{
				_callback(false);
			}
		}
	}
	
	_callback(true);
}

void TF2DHooker::StaticOutputDebugStringWSubst(LPCWSTR lpszFmt)
{
	get_Instance()->OutputDebugStringWSubst(lpszFmt);
}

void TF2DHooker::Hook(PageChangeCallbackFn pageChangeCallback)
{
	_callback = pageChangeCallback;

	HANDLE hProc = GetProcessByName(L"Manila2D.exe");

	/* GODMODE ON */
	BOOL  bOldKMode = SetKMode ( TRUE );
	DWORD dOldPerms = SetProcPermissions ( 0xFFFFFFFF );

	/* found? */
	if ( hProc )
	{
		/* found imports to patch */
		if ( 0 == callOutputDebugStringWOrg )
		{
			HMODULE coreDll = GetModuleHandle( L"coredll.dll" );
			callOutputDebugStringWOrg = ( DWORD ) GetProcAddress ( coreDll, L"OutputDebugStringW" );
		}

		/* patch imports */
		ic_PatchProcImports (hProc, (DWORD)callOutputDebugStringWOrg, (DWORD)StaticOutputDebugStringWSubst);
	}
	/* GODMODE OFF */
	SetProcPermissions ( dOldPerms );
	SetKMode ( bOldKMode );
}

void TF2DHooker::UnHook()
{
	HANDLE hProc = GetProcessByName(L"Manila2D.exe");

	/* found? */
	if ( hProc )
	{
		ic_PatchProcImports ( hProc, (DWORD)StaticOutputDebugStringWSubst, (DWORD)callOutputDebugStringWOrg);
	}
}